package com.koalton.steward.flow.dao;

import com.koalton.steward.common.util.SequenceUtil;
import com.koalton.steward.flow.model.Flow;
import com.koalton.steward.flow.model.ItemType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by koalton on 2017/7/11.
 */
@Repository
public class FlowDaoImpl implements FlowDao {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  public void insert(Flow flow) {
    StringBuilder insert = new StringBuilder();
    insert.append("INSERT INTO FLOW(");
    insert.append("id,item_id,amount,happend_date,recorder_id,flow_owner_id,remark");
    insert.append(") values(?,?,?,?,?,?,?)");

    jdbcTemplate.update(insert.toString(),
        flow.getID(), flow.getItemID(), flow.getAmount(),
        flow.getHappendDate(), flow.getRecorderID(),
        flow.getFlowOwnerID(), flow.getRemark());
  }

  @Override
  public void insert(List<Flow> flows) {

  }


  @Override
  public Flow query(Long flowID) {
    StringBuilder query = new StringBuilder();
    query.append(
        "select id,item_id,amount,record_time,happend_date,recorder_id,flow_owner_id,remark ");
    query.append(" from flow where id = ? ");

    Map<String, Object> map = jdbcTemplate.queryForMap(query.toString(), new Object[]{flowID});
    Flow flow = new Flow();
    if (map.isEmpty()) {
      return null;
    }
    flow.setID((Long) map.get("id"));
    flow.setItemID((Integer) map.get("item_id"));
    flow.setAmount((BigDecimal) map.get("amount"));
    flow.setHappendDate((Date) map.get("happend_date"));

    flow.setRecorderID((Long) map.get("recorder_id"));
    flow.setFlowOwnerID((Long) map.get("flow_owner_id"));
    flow.setRemark((String) map.get("remark"));
    return flow;
  }

  @Override
  public List<Flow> query(ItemType itemType) {
    return null;
  }

  @Override
  public List<Flow> query(ItemType itemType, Date happendDateStart, Date happendDateEnd) {
    return null;
  }

  public int test() {
    int count = jdbcTemplate.queryForObject("select count(*) from flow ", Integer.class);
    return count;
  }
}
